//
//  Fraction.m
//  Text
//
//  Created by 完美 on 15/10/15.
//  Copyright (c) 2015年 WJN. All rights reserved.
//

#import "Fraction.h"

@implementation Fraction{
    NSInteger _numerator;
    NSInteger _denominator;
}
-(instancetype)initWithNumerator:(NSInteger)numberator withDenominator:(NSInteger)denominator{
    self = [super init];
    if(self){
    _denominator = denominator;
    _numerator = numberator;
    }
    return self;
}
+(instancetype)FractionwithNumerator:(NSInteger)numberator withDenominator:(NSInteger)denominator{
    Fraction *fraction = [[Fraction alloc]initWithNumerator:numberator withDenominator:denominator];
    return fraction;
}

-(void)print{
    printf("  %ld\n ---\n  %ld\n", _numerator, _denominator);
}

-(void)reduce{
    NSInteger numUp = _numerator;
    NSInteger numDown = _denominator;
//当分子为0的时候直接退出，无论方法是否有分会之，当执行到return的时候直接退出方法，之下的代码不会执行
    if(_numerator == 0){
        return;
    }
// 求最大公约数-辗转相除
    while(numUp % numDown){
        NSInteger temp = numUp % numDown;
        numUp = numDown;
        numDown = temp;
    }
    _numerator /= numDown;
    _denominator /= numDown;
}

-(NSInteger)numberator{
    return _numerator;
}
-(NSInteger)denominator{
    return _denominator;
}
//加法实现
-(Fraction *)addFraction:(Fraction *)anotherFaction{
    NSInteger numerataor = _numerator * [anotherFaction denominator] + _denominator * [anotherFaction numberator];
    NSInteger denominator = _denominator *[anotherFaction denominator];
 
    Fraction *result = [[Fraction alloc]initWithNumerator:numerataor withDenominator:denominator];
    [result reduce];
    return result;
}
//乘法实现
-(Fraction *)MulFraction:(Fraction *)anotherFraction{
    NSInteger numerator = _numerator * [anotherFraction numberator];
    NSInteger denominator = _denominator * [anotherFraction denominator];
    Fraction *result = [[Fraction alloc]initWithNumerator:numerator withDenominator:denominator];
    [result reduce];
    return result;
}
//减法实现
-(Fraction *)SubFraction :(Fraction *)anotherFraction{
    NSInteger numerator = _numerator * [anotherFraction denominator] - [anotherFraction numberator]*
    _denominator;
    NSInteger denominator = _denominator *[anotherFraction denominator];
    Fraction *result =[[Fraction alloc]initWithNumerator:numerator withDenominator:denominator];
    [result reduce];
    return result;
}
 //除法实现
-(Fraction *)DivisionFraction :(Fraction *)anotherFraction{
    if([anotherFraction numberator] == 0)
       return 0;
    NSInteger numerator = _numerator * [anotherFraction denominator];
    NSInteger denominator = _denominator *[anotherFraction numberator];
    Fraction *result = [[Fraction alloc]initWithNumerator:numerator withDenominator:denominator];
    [result reduce];
    return result;
    }


@end
